package net.cardgame.orcalecard;

import java.io.File;
import java.lang.reflect.Type;

import jp.jma.oraclecard.R;
import net.cardgame.oraclecard.service.ServiceUpdateFileConfig;
import net.cardgame.orcalecard.bean.SettingApp;
import net.cardgame.orcalecard.pref.SecurePreferences;
import net.cardgame.orcalecard.utils.ConstantValue;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * Màn hình Splash khi khởi động app
 */
public class SplashActivity extends Activity {
	private static String TAG = SplashActivity.class.getName();
	private static long SLEEP_TIME = 2000; // Sleep for some time
	/**
	 * The thread to process splash screen events
	 */
	private Thread mSplashThread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash_layout);
		startService(new Intent(this, ServiceUpdateFileConfig.class));
		// The thread to wait for splash screen events
		mSplashThread = new Thread() {
			@Override
			public void run() {
				try {
					synchronized (this) {
						// Wait given period of time or exit on touch
						wait(SLEEP_TIME);
					}
				} catch (InterruptedException ex) {
				}
				handler.sendMessage(handler.obtainMessage());
			}
		};

		mSplashThread.start();
		createAppFolder();
		loadSettingApp();
	}

	void loadSettingApp() {
		SettingApp setting = new SettingApp();
		setting.setDefault();
		Gson gson = new Gson();
		Type SettingAppType = new TypeToken<SettingApp>() {
		}.getType();
		SecurePreferences appPreferences = new SecurePreferences(this,
				ConstantValue.APP_PREFERENCES,
				ConstantValue.PREFERENCES_SECRET_KEY, true);
		if (!appPreferences.containsKey(ConstantValue.SETTING_KEY)) {
			String save = gson.toJson(setting, SettingAppType);
			appPreferences.put(ConstantValue.SETTING_KEY, save);
		}

	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			Intent intent = new Intent(SplashActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
		};
	};

	private void createAppFolder() {
		File file = new File(ConstantValue.getBasePatchApp(this));
		if (!file.exists())
			file.mkdirs();
	}

	/**
	 * Processes splash screen touch events
	 */
	@Override
	public boolean onTouchEvent(MotionEvent evt) {
		if (evt.getAction() == MotionEvent.ACTION_DOWN) {
			synchronized (mSplashThread) {
				mSplashThread.notifyAll();
			}
		}
		return true;
	}

}
